package com.wgts.wgts.mvp.view.activity.mycenter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wgts.wgts.ActivityStack;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.dialog.WonderLoadingDialog;
import com.wgts.wgts.control.eventbus.EditNikeNameEventBus;
import com.wgts.wgts.control.eventbus.LoginEvenBus;
import com.wgts.wgts.control.eventbus.PayEvenBus;
import com.wgts.wgts.control.eventbus.PutForwardEventBus;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerMyCenterFragmentComponet;
import com.wgts.wgts.dagger.module.MyCenterFragmentModule;
import com.wgts.wgts.mvp.presenter.IMyCenterFragmentPersenter;
import com.wgts.wgts.mvp.view.IMyCenterFragmentView;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.mvp.view.activity.message.MessageDetailsActivity;
import com.wgts.wgts.mvp.view.activity.myorder.MyOrderActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.AssetDetailActivity;
import com.wgts.wgts.mvp.view.activity.shopkeeper.PutForwardActivity;
import com.wgts.wgts.mvp.view.activity.store.StoreActivity;
import com.wgts.wgts.mvp.view.activity.wgtsteam.WgtsMyTeamActivity;
import com.wgts.wgts.netmodle.resp.AppUpdateEntity;
import com.wgts.wgts.netmodle.resp.MyCenterMessageEntity;
import com.wgts.wgts.react.MD5Util;
import com.wgts.wgts.thirdParty.push.PushTools;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.InstallUtil;
import com.wgts.wgts.tools.UpdateDialogFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

import static com.umeng.socialize.utils.ContextUtil.getPackageName;

/*
 *
 *
 *   data:2018/9/2717:41
 *
 */public class MyCenterFragment extends LazyBaseFragment implements IMyCenterFragmentView {
    @BindView(R.id.my_center_head)
    CircleImageView myCenterHead;
    @BindView(R.id.my_center_name)
    TextView myCenterName;
    @BindView(R.id.my_center_status_iamge)
    ImageView myCenterStatusIamge;
    @BindView(R.id.my_center_status_text)
    TextView myCenterStatusText;
    @BindView(R.id.my_center_watch_message_ly)
    RelativeLayout myCenterWatchMessageLy;
    @BindView(R.id.my_center_head_ly)
    LinearLayout myCenterHeadLy;
    @BindView(R.id.balance)
    TextView balance;
    @BindView(R.id.cursh_ly)
    LinearLayout curshLy;
    @BindView(R.id.today_income_text)
    TextView todayIncomeText;
    @BindView(R.id.all_income_text)
    TextView allIncomeText;
    @BindView(R.id.all_crush_text)
    TextView allCrushText;
    @BindView(R.id.coin_ly)
    RelativeLayout coinLy;
    @BindView(R.id.discount_coupon_ly)
    RelativeLayout discountCouponLy;
    @BindView(R.id.my_order_ly)
    RelativeLayout myOrderLy;
    @BindView(R.id.shipping_address_ly)
    RelativeLayout shippingAddressLy;
    @BindView(R.id.my_collect_ly)
    RelativeLayout myCollectLy;
    @BindView(R.id.system_setting_ly)
    RelativeLayout systemSettingLy;
    @BindView(R.id.app_version_text)
    TextView appVersionText;
    @BindView(R.id.help_center_ly)
    RelativeLayout helpCenterLy;
    @BindView(R.id.my_center_system_ly)
    LinearLayout myCenterSystemLy;
    @BindView(R.id.quit_login_ly)
    LinearLayout quitLoginLy;
    Unbinder unbinder;

    @Inject
    IMyCenterFragmentPersenter persenter;
    @BindView(R.id.vip_status)
    RelativeLayout vipStatus;
    @BindView(R.id.vip_status_image)
    ImageView vipStatusImage;
    @BindView(R.id.violator_ly)
    LinearLayout violatorLy;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private MyCenterMessageEntity messageEntity;

    private int MyCenterFragmentResult = 3;

    private WonderLoadingDialog dialog;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            persenter.getMyCenterResult();
            initView();
        }
    }

    @Override
    protected void loadData() {
    }

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.my_center_fragment, null);
        unbinder = ButterKnife.bind(this, view);

        PackageManager manager = getContext().getPackageManager();
        String name = null;
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
            appVersionText.setText("v" + info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        EventBus.getDefault().register(this);

        return view;
    }

    @Override
    public void init() {
        DaggerMyCenterFragmentComponet
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .myCenterFragmentModule(new MyCenterFragmentModule(this))
                .build()
                .inject(this);
    }

    private void initView() {
        dialog = new WonderLoadingDialog(getActivity());
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadmore(false);
        refresh();
        switch (AppInfor.getInstance().getUserState()) {
            case 0:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_1);
                myCenterStatusText.setText("普通用户");
                break;
            case 1:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_2);
                myCenterStatusText.setText("金牌推手");
                if (AppInfor.getInstance().getVipFansCount() >= 50) {
                    // 金牌城主
                    vipStatusImage.setImageResource(R.mipmap.icon_grade_5);
                }
                break;
            case 2:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_3);
                //myCenterStatusIamge.setImageResource(R.mipmap.ic_store_store_white);
                myCenterStatusText.setText("钻石推手");
                if (AppInfor.getInstance().getSvipFansCount() >= 20) {
                    //钻石城主
                    vipStatusImage.setImageResource(R.mipmap.icon_grade_4);
                } else {
                    if (AppInfor.getInstance().getVipFansCount() >= 50) {
                        //金牌城主
                        vipStatusImage.setImageResource(R.mipmap.icon_grade_5);
                    }
                }
                break;
            case 3:
                myCenterStatusIamge.setImageResource(R.mipmap.ic_data_rudder_white);
                myCenterStatusText.setText("高级会员");
                break;
            case 4:
                myCenterStatusIamge.setImageResource(R.mipmap.ic_data_rudder_white);
                myCenterStatusText.setText("高级会员");
                break;
        }
    }

    @Override
    public void onError(int status, String msg) {
        refreshLayout.finishRefresh();
        MoHuToast.showToast(msg);
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.my_center_watch_message_ly, R.id.discount_coupon_ly,
            R.id.shipping_address_ly, R.id.my_collect_ly, R.id.system_setting_ly,
            R.id.help_center_ly, R.id.cursh_ly, R.id.quit_login_ly
            , R.id.my_order_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_center_watch_message_ly:
                jump(MyCenterMessageActivity.class);
                break;
            case R.id.discount_coupon_ly:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
                    Intent intent1 = new Intent(getActivity(), MessageDetailsActivity.class);
                    startActivity(intent1);
                } else {
                    Intent intent2 = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.shipping_address_ly:
                jump(ShippingAddressActivity.class);
                break;
            case R.id.my_collect_ly:
                jump(WgtsMyTeamActivity.class);
                break;
            case R.id.system_setting_ly:
                Intent intent = new Intent(getActivity(), AssetDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.help_center_ly:
                //updateInfo();
                break;
            case R.id.cursh_ly:
                jump(PutForwardActivity.class);
                break;
            case R.id.quit_login_ly:
                PushTools.getInstance().setAlias(getContext(), "");
                persenter.quitLogin();
                break;
            case R.id.my_order_ly:
                jumpWithDate(MyOrderActivity.class, 0);
                break;
        }
    }

    private void jumpStore(Class<? extends Activity> cls) {
        Intent intent = new Intent(getActivity(), cls);
        intent.putExtra(StoreActivity.USER_TYPE, "MY_CENTER");
        startActivity(intent);
    }

    private void jumpWithDate(Class<? extends Activity> cls, Parcelable data) {
        Intent intent = new Intent(getActivity(), cls);
        intent.putExtra("date", data);
        startActivity(intent);
    }

    private void jump(Class<? extends Activity> clz) {
        Intent intent = new Intent(getActivity(), clz);
        //startActivityForResult(intent, MyCenterFragmentResult);
        startActivity(intent);
    }

    private void jumpWithDate(Class<? extends Activity> cls, int position) {
        Intent intent = new Intent(getActivity(), cls);
        intent.putExtra("position", position);
        startActivity(intent);
    }

    @Override
    public void getMyCenterResult(MyCenterMessageEntity entity) {
        refreshLayout.finishRefresh();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        messageEntity = new MyCenterMessageEntity();
        messageEntity = entity;
        //MoHuGlide.getInstance().glideImg(getContext(), entity.userImage, myCenterHead);
        myCenterName.setText(entity.userNickName);
        balance.setText(entity.availableBalance);
        todayIncomeText.setText(entity.todayIncome);
        allIncomeText.setText(entity.totalIncome);
        allCrushText.setText(entity.totalWithdraw);
        switch (AppInfor.getInstance().getIllegal()) {
            case 0:
                violatorLy.setVisibility(View.GONE);
                break;
            case 1:
                violatorLy.setVisibility(View.VISIBLE);
                break;
        }
        switch (AppInfor.getInstance().getUserState()) {
            case 0:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_1);
                myCenterStatusText.setText("普通用户");
                break;
            case 1:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_2);
                myCenterStatusText.setText("金牌推手");
                if (AppInfor.getInstance().getVipFansCount() >= 50) {
                    vipStatusImage.setImageResource(R.mipmap.icon_grade_5);
                }
                break;
            case 2:
                myCenterStatusIamge.setImageResource(R.mipmap.icon_grade_3);
                myCenterStatusText.setText("钻石推手");
                if (AppInfor.getInstance().getSvipFansCount() >= 20) {
                    vipStatusImage.setImageResource(R.mipmap.icon_grade_4);
                } else {
                    if (AppInfor.getInstance().getVipFansCount() >= 50) {
                        vipStatusImage.setImageResource(R.mipmap.icon_grade_5);
                    }
                }
                break;
            case 3:
                myCenterStatusIamge.setImageResource(R.mipmap.ic_data_rudder_white);
                myCenterStatusText.setText("高级会员");
                break;
            case 4:
                myCenterStatusIamge.setImageResource(R.mipmap.ic_data_rudder_white);
                myCenterStatusText.setText("高级会员");
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyCenterFragmentResult) {
            //MoHuGlide.getInstance().glideImg(getContext(), AppInfor.getInstance().getUserHead(), myCenterHead);
            myCenterName.setText(AppInfor.getInstance().getUserName());
        }
    }

    @Override
    public void quitLogin() {
        for (BaseActivity activity : ActivityStack.getInstance().getActivities()) {
            if (activity != null && activity instanceof MoHuMainActivity) {
                ((MoHuMainActivity) activity).changeViewPage(0);
                ((MoHuMainActivity) activity).UpdateSuccess();
                EventBus.getDefault().post(new PayEvenBus());
                EventBus.getDefault().post(new LoginEvenBus());
            }
        }
    }

    @Override
    public void appUpdate(AppUpdateEntity entity) {
        String path = Environment.getExternalStorageDirectory() + "/WgtsDownFiles/" + MD5Util.encrypt(entity.url) + ".apk";

        //InstallUtil.getInstance(this, path);

        UpdateDialogFragment updateDialogFragment;

        updateDialogFragment = UpdateDialogFragment.setToastMessage(entity);

        UpdateDialogFragment.setmInstallUtil(InstallUtil.getInstance(getActivity(), path));

        if (entity.forceUpgrade == 1) {

            updateDialogFragment.show(getActivity().getSupportFragmentManager(), "");

        } else {
            if (entity.upgrade == 1) {

                updateDialogFragment.show(getActivity().getSupportFragmentManager(), "");
            }
        }
    }

    private void updateInfo() {
        PackageManager manager = getActivity().getPackageManager();
        String name = null;
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        name = info.versionName;
        persenter.appUpdate("", name);
    }

    private void refresh(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (dialog != null) {
                    dialog.show();
                }
                persenter.getMyCenterResult();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PutForwardEventBus event) {
        persenter.getMyCenterResult();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EditNikeNameEventBus event) {
        persenter.getMyCenterResult();
    }

}
